<?php

namespace App\Http\Controllers\Api;

use App\Constants\ContentReCommendConstant;
use App\Constants\MemberTaskConstant;
use App\Constants\MiniProgramConstant;
use App\Constants\TagConstant;
use App\Events\DailyTask;
use App\Http\Requests\Api\IdMustRequest;
use App\Http\Resources\TopicResource;
use App\Models\Tag;
use App\Models\Theme;
use App\Models\Topic;
use Illuminate\Http\Request;

use App\Models\Favorite;
use App\Models\Member;
use App\Models\Publisher;
use App\Models\TopicComment;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class TopicController extends Controller
{

    /**
     * 发布帖子
     */
    public function publish(Request $request)
    {
        $validatedData = Validator::make($request->all(), [
            'title'   => 'required|max:200|string',
            'content' => 'required|max:1000|string',
            'themes'  => ['required', function ($attribute, $value, $fail) {
                $arr = array_filter(explode(',', $value));
                if (count($arr) > 5) {
                    $fail('话题不能超过5个');
                } else {
                    foreach ($arr as $item) {
                        if (Str::length($item) > 10) {
                            $fail('话题不能超过10个字');
                        }
                    }
                }
            }],
            'tag_id'  => 'required|min:0|integer',
        ], [
            'title.required'   => '标题不能为空',
            'content.required' => '内容不能为空',
            'content.max'      => '不能超过1000个字数',
            'themes.required'  => '话题不能为空',
            'tag_id.required'  => '标签不能为空',
        ])->validate();

        $themes = array_filter(explode(',', $validatedData['themes']));
        unset($validatedData['themes']);

        DB::beginTransaction();

        try {
            $themeIdArr = [];

            foreach ($themes as $name) {
                $model = Theme::where('name', $name)->first();
                if ($model) {
                    $model->increment('use_sum');

                } else {
                    $model = Theme::create(['name' => $name, 'use_sum' => 1, 'mini_type' => $this->getMiniType()]);
                }
                $themeIdArr[] = $model->id;
            }

            $topic = Topic::create(array_merge($validatedData, [
                'files'     => $request->input('files', ''),
                'member_id' => auth('api')->user()->id,
                'status'    => boolval(auth('api')->user()->publisher),
                'mini_type' => $this->getMiniType(),
            ]));

            $topic->topicTheme()->sync($themeIdArr);
            event(new DailyTask($this->getMiniType(), auth('api')->user()->id, MemberTaskConstant::SLUG_BY_PUBLISH));

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            log_exception('发布帖子失败', $e);
            return $this->error('发布失败');
        }

        return $this->success('发布成功');
    }

    /**
     * 我的帖子
     *  $status 状态值
     */
    public function list(Request $request)
    {
        // dd($request->user());
        //获取用户id
        $member_id = auth('api')->user()->id;
        // $member_id = 5;
        //接收参数
        $status = $request->input('status');
        if (!is_numeric($status)) {
            return $this->success('参数不是整数');
        }
        // $topic= new Topic();
        // $list= $topic->where(['status'=>$status,'member_id'=>$member_id])->paginate();
        // $list = DB::table('topics')
        $list = Topic::leftJoin('members', 'topics.member_id', '=', 'members.id')
            ->select('topics.*', 'members.avatar', 'members.nickname')
            ->where(['topics.status' => $status, 'topics.member_id' => $member_id])
            ->orderBy('created_at', 'desc')
            ->paginate();
        if ($list->isEmpty()) {
            return $this->success('暂时没有数据');
        }

        foreach ($list as $key => $value) {
            $data[] = [
                'id'            => $value->id,
                'member_id'     => $value->member_id,
                'title'         => $value->title,
                'content'       => $value->content,
                'files'         => $value->files == '' ? [] : explode(',', $value->files),
                'relay_count'   => $value->relay_count,
                'fav_count'     => $value->fav_count,
                'is_hot'        => $value->is_hot,
                'created_at'    => date("m月d日 H:i", strtotime($value->created_at)),
                'updated_at'    => date("m月d日 H:i", strtotime($value->updated_at)),
                'deleted_at'    => date("m月d日 H:i", strtotime($value->deleted_at)),
                'avatar'        => $value->avatar,
                'nickname'      => $value->nickname,
                'is_fav'        => Favorite::where(['member_id' => $member_id, 'topic_id' => $value->id])->count(),
                'is_vip'        => $this->isVip($value->member_id),
                'if_hot'        => ($value->status == 1 && $value->is_hot == 0) ?? false,
                'if_cancel_hot' => ($value->status == 1 && $value->is_hot == 1) ?? false,
                'if_delete'     => true,
            ];
        }
        return $this->success('ok', $data);
    }

    /**
     * 热门帖子
     */
    public function hot(Request $request)
    {
        $memberId = auth('api')->user()->id ?? 0;

        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_TOPIC_SWITCH) ?? 0;

        $query = Topic::with(['member', 'topicTag:id,name', 'topicTheme:id,name'])
            ->when($switch != 1, function ($q) {
                return $q->where('mini_type', $this->getMiniType());
            })
            ->when(isset($memberId), function ($q) use ($memberId) {
                return $memberId > 0 ?
                    $q->whereRaw('IF(member_id = ?, status < ?, status = ?)', [$memberId, 2, 1]) :
                    $q->where('status', '=', true);
            });

        $tagId = $request->input('tag_id', 0);
        $keyword = trim($request->input('keyword', ''));
        $themeId = $request->input('theme_id', 0);

        if ($keyword) {
            $query->where('content', 'REGEXP', cutKeyword($keyword));
        }

        if ($themeId) {
            $query->whereHas('topicTheme', function ($q) use ($themeId) {
                $q->where('id', '=', $themeId);
            });
        }

        if (!$keyword && !$themeId) {
            if ($tagId) {
                $query->where('tag_id', '=', $tagId);
            } else {
                $newQuery = clone $query;
                $settings = getMiniSettings($this->getMiniType(), ContentReCommendConstant::GROUP);
                $day = $settings[ContentReCommendConstant::TOPIC_TJ_DAY] ?? 30;

                $query->where('is_hot', '=', true);
                $query->whereDate('created_at', '>=', now()->subDays($day)->format('Y-m-d'));
            }
        }

        $list = $query
            ->withCount(['topicComment' => function ($q) {
                $q->where('status', '=', true);
            }])
            ->orderByDesc('id')
            ->paginate();

        if (!$list->count() && isset($newQuery)) {
            $list = $newQuery
                ->withCount(['topicComment' => function ($q) {
                    $q->where('status', '=', true);
                }])
                ->orderByDesc('id')
                ->paginate();
        }

        return $this->success('返回成功', TopicResource::collection($list));
    }

    /**
     * 帖子详情
     */
    public function detail(Request $request)
    {
        $member_id = 0;
        //获取用户id
        if (auth('api')->check()) {
            $member_id = auth('api')->user()->id;
        }

        //获取参数
        $topic_id = $request->input('topic_id');
        if (!is_numeric($topic_id)) {
            return $this->error('数据不合法,请输入整数');
        }

        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_TOPIC_SWITCH) ?? 0;

        //帖子表
        $list = Topic::leftJoin('members', 'topics.member_id', '=', 'members.id')
            ->select('topics.*', 'members.avatar', 'members.nickname')
            ->where(['topics.id' => $topic_id])
            ->when($switch != 1, function ($q) {
                return $q->where('topics.mini_type', $this->getMiniType());
            })
            ->get();
        // if ($list->isEmpty()) {
        //         return $this->success('暂时没有数据');
        // }
        // 是否楼主判断
        $user = Topic::where('id', $topic_id)->first();
        $userMember_id = $user->member_id;

        //帖子回复表
        // $res = DB::table('topic_comments')
        $res = TopicComment::leftJoin('members', 'topic_comments.member_id', '=', 'members.id')
            ->select('topic_comments.member_id', 'topic_comments.id', 'topic_comments.topic_id', 'topic_comments.content', 'topic_comments.fav_count', 'topic_comments.status', 'topic_comments.created_at', 'members.avatar', 'members.nickname')
            ->where(['topic_comments.topic_id' => $topic_id])
            ->when(isset($member_id), function ($q) use ($member_id) {
                return $member_id > 0 ?
                    $q->whereRaw('IF(topic_comments.member_id = ?, topic_comments.status < ?, topic_comments.status = ?)', [$member_id, 2, 1]) :
                    $q->where('topic_comments.status', 1);
            })
//            ->whereRaw('IF(topic_comments.member_id = ?, topic_comments.status < ?, topic_comments.status = ?)', [$member_id, 2, 1])
            ->orderBy('created_at', 'desc')
            ->get();
        foreach ($res as $key => $value) {
            $topic_comment[] = [
                'id'         => $value->id,
                'member_id'  => $value->member_id,
                'content'    => $value->content,
                'fav_count'  => $value->fav_count,
                'created_at' => date('m月d日', strtotime($value->created_at)),
                'avatar'     => $value->avatar,
                'nickname'   => $value->nickname,
                'author'     => $value->member_id == $userMember_id ? '楼主' : '',
                'topic_id'   => $value->topic_id,
                'is_fav'     => $member_id == 0 ? 0 : Favorite::where(['member_id' => $value->member_id, 'topic_comment_id' => $value->id])->count(),
                'is_vip'     => $this->isVip($value->member_id),
                'status'     => $value->status == 1,

            ];
        };
        if (empty($topic_comment)) {
            $topic_comment = [];
        }

        foreach ($list as $key => $value) {
            $data[] = [
                'id'            => $value->id,
                'member_id'     => $value->member_id,
                'title'         => $value->title,
                'content'       => $value->content,
                'files'         => $value->files == '' ? [] : explode(',', $value->files),
                'relay_count'   => $value->relay_count,
                'fav_count'     => $value->fav_count,
                'is_hot'        => $value->is_hot,
                'created_at'    => date("m月d日 H:i", strtotime($value->created_at)),
                'updated_at'    => date("m月d日 H:i", strtotime($value->updated_at)),
                'deleted_at'    => date("m月d日 H:i", strtotime($value->deleted_at)),
                'avatar'        => $value->avatar,
                'nickname'      => $value->nickname,
                'is_fav'        => $member_id == 0 ? 0 : Favorite::where(['member_id' => $member_id, 'topic_id' => $value->id])->count(),
                'is_delete'     => $value->member_id == $member_id ? true : false,
                'is_vip'        => $this->isVip($value->member_id),
                'topic_comment' => $topic_comment,
                'can_relay'     => $value->status == 1
            ];
        }

        return $this->success('ok', $data);
    }

    /**
     * 帖子详情删除
     * */
    public function delete(Request $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_TOPIC_SWITCH) ?? 0;

        $topic_id = $request->input('topic_id');
        $topic = Topic::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($topic_id);
        if (!$topic) {
            return $this->error('帖子不存在');
        }
        $topic->delete();
        $topic->topicComment()->delete();
        $topic->topicTheme()->detach();
        if ($topic->trashed()) {
            return $this->success('帖子删除成功');
        } else {
            return $this->error('帖子删除失败');
        }
    }

    public function favor(IdMustRequest $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_TOPIC_SWITCH) ?? 0;

        $topic = Topic::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($request->id);
        $user = auth('api')->user();
        if ($user->favoriteTopics()->find($request->id) || !$topic) {
            return $this->success('success');
        }

        $user->favoriteTopics()->attach($topic);
        $topic->increment('fav_count');
        $topic->member->increment('favs_count');

        return $this->success('success');
    }

    public function disfavor(IdMustRequest $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_TOPIC_SWITCH) ?? 0;

        $topic = Topic::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($request->id);
        $user = auth('api')->user();
        if (!$user->favoriteTopics()->find($request->id) || !$topic) {
            return $this->success('success');
        }

        $user->favoriteTopics()->detach($topic);
        $topic->decrement('fav_count');
        $topic->member->decrement('favs_count');

        return $this->success('success');
    }

    public function relay(IdMustRequest $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_TOPIC_SWITCH) ?? 0;

        $topic = Topic::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->where('status', '=', true)->find($request->id);

        if (!$topic) {
            return $this->success('success');
        }

        $topic->increment('relay_count');
        if (auth('api')->check()) {
            auth('api')->user()->increment('relay_count');
            event(new DailyTask($this->getMiniType(), auth('api')->user()->id, MemberTaskConstant::SLUG_BY_RELAY));
        }

        return $this->success('success');
    }

    /**
     *判断是否为vip
     *$member_id 用户id
     */
    public function isVip($member_id)
    {
        $res = Member::find($member_id)->toArray();
        $openid = Publisher::where('open_id', $res['open_id'])->count();
        return $openid == 1 ? 1 : 0;

    }

    public function setHot(Request $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_TOPIC_SWITCH) ?? 0;

        $id = $request->input('id');
        $is_hot = $request->input('is_hot', 1);
        $topic = Topic::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($id);
        if (!$topic) {
            return $this->error('帖子不存在');
        }
        $topic->is_hot = $is_hot;
        if ($topic->save()) {
            return $this->success('操作成功');
        } else {
            return $this->error('操作失败');
        }
    }

    public function tags()
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_TOPIC_SWITCH) ?? 0;

        $list = Tag::where(['type' => TagConstant::TAG_BY_TOPIC])
            ->when($switch != 1, function ($q) {
                return $q->where('mini_type', $this->getMiniType());
            })
            ->where('status', '=', true)
            ->orderByDesc('sort')
            ->select('name', 'id')
            ->get();

        return $this->_success(compact('list'));
    }
}
